/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.fancy.applicaiton.tools.htmltox.wrapper.htmltopdf.config;

import com.fancy.applicaiton.tools.htmltox.wrapper.htmltopdf.source.ContentSource;
import com.fancy.applicaiton.tools.htmltox.wrapper.htmltopdf.source.Source;
import com.fancy.applicaiton.tools.htmltox.wrapper.htmltopdf.source.UrlSource;
import com.fancy.applicaiton.tools.htmltox.wrapper.util.OsUtil;
import com.fancy.applicaiton.tools.htmltox.wrapper.util.UUIDUtil;



import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.FileUtils;


/**
 *
 * @author wison.wu
 */
public class WapperConfig {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());


    /**
     * 获取可执行文件(only windows)
     * @return 
     */
    public String getExecutePath(){
        String path = System.getProperty("user.dir");
        String dir= "";
        String exec = "";
        if(OsUtil.WINDOWS){
            dir = "windows";
            exec ="wkhtmltopdf.exe";
        }else if(OsUtil.LINUX){
            dir = "linux";
            exec ="wkhtmltopdf.exe";
        }
        String libPath ="\\lib\\"+dir+"\\html2pdf\\bin\\"+exec;
        path+=libPath;
        return path;
    }


    private List<Source> sourceList = new ArrayList<>();
    public List<Source> getSourceList() {
        return sourceList;
    }

    private String[] getCommandArray() {
        String execute = getExecutePath();
        List<String> commandLine = new ArrayList<>();
        commandLine.add(execute);       //执行文件
        sourceList.forEach(source -> {
            if(source instanceof UrlSource){
                UrlSource urlSource = (UrlSource)source;
                commandLine.add(urlSource.getSource());
            }else if(source instanceof ContentSource){

                ContentSource contentSource = (ContentSource)source;
                String path = createTempHtmlFile(contentSource.getSource());
                contentSource.setSource(path);
                commandLine.add(contentSource.getSource());
            }

        });
        return commandLine.toArray(new String[commandLine.size()]);
    }

    private String createTempHtmlFile(String source){
        String path = null;
        try {
            File temp = File.createTempFile("fancy-html2x-"+ UUIDUtil.random(),".html");
            FileUtils.writeStringToFile(temp, source, "UTF-8");
            path= temp.getAbsolutePath();
        } catch (IOException e) {
            logger.error("创建临时文件出错，"+e);
        }
        return path;
    }

    public String getCommmand(){
        return String.join(" ", getCommandArray());
    }
}
